package com.soundai.skill.helloworld.socket;

import com.alibaba.fastjson.JSONArray;
import com.soundai.skill.helloworld.HttpHelper.HttpClientHelper;
import com.soundai.skill.helloworld.config.SocketConfig;
import com.soundai.skill.helloworld.config.uriConfig;
import com.soundai.skill.helloworld.entity.MsgHeader;
import com.soundai.skill.helloworld.helper.Base64Util;
import com.soundai.skill.helloworld.helper.GZipHelper;
import com.soundai.skill.helloworld.helper.RandomUtils;
import com.soundai.skill.helloworld.helper.Utils;
import com.soundai.skill.helloworld.log.logC;
import net.sf.json.JSON;
import net.sf.json.JSONObject;
import net.sf.json.JSONString;

import java.io.*;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.SocketAddress;

/**
 * socket 客户端
 */
public class SocketClient {

    //数据解压缩实例化



    public static void main(String[] args) {
        /**
         * 在main方法中启动应用程序
         */

        for (int i = 0; i < 1; i++) {
           //long start, end;
            //start = System.currentTimeMillis();
            //String returnMsg = sendBySocket("connect user:walifire_Server type:other msg:walifire_23123233E123#http12345678;8;8135;6251850005610;2,0$/r$\r\n","47.107.66.121",9802);

            //8;8135 开灯 ， ;8;8145; 关灯
            //connect user:walifire_Server type:other msg:walifire_CsT1fLGP#http81d283cc6862479fa425cef78755d71a;8:8135;6251850005610;$/r$

            //String uri = String.format(SocketConfig.connectUri,"walifire_Server", RandomUtils.getShortUuid(),RandomUtils.uuid(),"8;8135","6251850005631");
            //String uri = String.format(SocketConfig.connectUri,"walifire_Server", RandomUtils.getShortUuid(),RandomUtils.uuid(),"8;8135","6251850005631");


            //设备列表
            //String uri = String.format(SocketConfig.connectUri, "walifire_Server", RandomUtils.getShortUuid(), RandomUtils.uuid(), "8;815", "0");
            //String uri = String.format(SocketConfig.connectUri,"walifire_Server", RandomUtils.getShortUuid(),RandomUtils.uuid(),"1;112","all");
           // GZipHelper zip = new GZipHelper();
           // String returnMsg = sendBySocket(uri, "47.107.66.121", 9802);
           // System.out.println("序号：" + i + "返回值：" + returnMsg);
            //System.out.println("解压数据："+Utils.decodeBase64(returnMsg));
            /*String[] arr = Utils.splitData(returnMsg, ";");
            for (int j = 0; j < arr.length; j++) {
                if (arr[j].toString().toLowerCase().equals("zip")) {
                    String newData = arr[j + 1].toString().substring(0, arr[j + 1].length() - 4);
                    System.out.println("newData:" + newData);
                    byte[] bytes = Utils.decodeByteBase64(newData);
                }
            }*/
           // end = System.currentTimeMillis();
          //  System.out.println("start time:" + start + "; end time:" + end + "; Run Time:" + (end - start) + "(ms)");

        }
        //System.out.println(requestHomeSocket());
    }

    /**
     * 智慧家庭Socket请求接口
     * @return
     */
    public static String requestHomeSocket(String conUser,String code,String args,String deviceid) {
        String ret = "";
        String uri = String.format(SocketConfig.connectUri, conUser, conUser,RandomUtils.getShortUuid(),deviceid, RandomUtils.uuid(), code, args);
        ret = sendBySocket(uri, SocketConfig.homeIp, SocketConfig.homePort);
        return ret;
    }

    public static String requestGitSocket(String conUser,String code,String args,String deviceid) {
        String ret = "";
        String uri = String.format(SocketConfig.connectUri, conUser, conUser,RandomUtils.getShortUuid(),deviceid, RandomUtils.uuid(), code, args);
        ret = sendBySocket(uri, SocketConfig.gitIp, SocketConfig.homePort);
        return ret;
    }

    public static String sendtts(String deviceid,String msg) {
        String ret = "";
        String code="5;513";
        String userId = "";
        try {
            msg=msg.replace(" ","");
            msg = Base64Util.encode(msg.getBytes("UTF-8"));
            String soundHostData = HttpClientHelper.doGet(String.format(uriConfig.soundHostUrl, deviceid));//请求音箱设备信息地址
            JSONObject jo = JSONObject.fromObject(soundHostData);
            String reCode = jo.get("code").toString();
            if (reCode.equals("true")) {
            JSONObject sh = JSONObject.fromObject(jo.get("data"));
            userId = sh.get("userid").toString();
            } else
                return "设备未添加绑定";

            userId=userId.substring(0,userId.indexOf("_"));
        } catch (Exception e) {
            e.printStackTrace();
        }

        String uri = String.format(SocketConfig.ttsUri, userId, userId,RandomUtils.getShortUuid(),deviceid, RandomUtils.uuid(), code, msg);
        ret = sendBySocket(uri, SocketConfig.homeIp, SocketConfig.homePort);
        //根据分号截取数据
        /*String[] arr = Utils.splitData(reponseMsg, ";");
        for (int j = 0; j < arr.length; j++) {
            if (arr[j].toString().toLowerCase().equals("zip")) {
                String newData = arr[j + 1].toString().substring(0, arr[j + 1].length() - 4);
                byte[] bytes = Utils.decodeByteBase64(newData);
                ret = new GZipHelper().uncompress(bytes);
            }
        }*/
        return ret;
    }

    /**
     * 登陆注册
     * @return
     */
    public static String regHome(String conUser,String regCode) {
        String ret = "";
        String uri = String.format(SocketConfig.regConnectUri, conUser,regCode,regCode);
        String reponseMsg = sendBySocket(uri, SocketConfig.homeIp, SocketConfig.homePort);
        //根据分号截取数据
       /* String[] arr = Utils.splitData(reponseMsg, ";");
        for (int j = 0; j < arr.length; j++) {
            if (arr[j].toString().toLowerCase().equals("zip")) {
                String newData = arr[j + 1].toString().substring(0, arr[j + 1].length() - 4);
                byte[] bytes = Utils.decodeByteBase64(newData);
                ret = new GZipHelper().uncompress(bytes);
            }
        }*/
        return ret;
    }

    /**
     * 采用socket连接向服务器发送消息，接受响应信息
     *
     * @param sendText
     * @param ip
     * @param port
     * @return
     */
    public static String sendBySocket(String sendText, String ip, int port) {
        String returnMsg = "";
       try {
            //System.out.println("开始建立socket连接");
           logC.writeFile("","发起服务器请求：" + sendText);
            Socket socket = new Socket(ip, port);
            socket.setSoTimeout(5000); //5秒钟
            InputStream inputStream = socket.getInputStream();
            InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "UTF-8");
            OutputStream outputStream = socket.getOutputStream();
           // System.out.println("连接服务端成功");
            outputStream.write(sendText.getBytes());
            outputStream.flush();

            BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
            returnMsg = bufferedReader.readLine();

            bufferedReader.close();
            inputStreamReader.close();
            inputStream.close();
            outputStream.close();
            socket.close();
           if (returnMsg.length()>0)
               returnMsg = new String(Base64Util.decode(returnMsg),"UTF-8");
        } catch (Exception ex) {
           logC.writeFile("","连接服务端出现异常：" + ex.toString());
           returnMsg = "{\"speek\":\"连接服务端出现异常\",\"sucess\":\"false\"}";
        }
        /*try {
            Socket sck = new Socket();
            SocketAddress socAddress = new InetSocketAddress(ip, port);
            sck.connect(socAddress, 10000);
            sck.setSoTimeout(10000);
            InputStream in = sck.getInputStream();
            OutputStream out = sck.getOutputStream();
            byte[] buffer = new byte[1000];
            out.write(sendText.getBytes());
            out.flush();
            int temp=0;
            for (int i=0;i<20;i++)
            {
                Thread.sleep(550);
                while(in.available()>0){
                    int numBytes=in.read(buffer);
                    temp = temp+numBytes;
                }

                if (temp>1) i=51;
            }
            if (temp>0)
            {
                returnMsg=new String(buffer,"UTF-8");
                returnMsg=returnMsg.substring(0,temp*2);
            }
            sck.close();
            sck=null;

        } catch (Exception ex) {

        }*/

        return returnMsg;
    }

    public static String requestNewSocket(String conUser,String code,String args,String deviceid) {
        String ret = "";
        String uri = conUser+"_"+RandomUtils.getShortUuid()+"#"+"sound"+deviceid+"#"+RandomUtils.uuid();
        args = uri+";"+code+";"+args;
        ResponseMsg response= new ResponseMsg();
        response.setHeader( new MsgHeader());
        response.getHeader().setBizCode(2810);
        response.getHeader().setToUserId(conUser);
        response.getHeader().setMac("sound"+deviceid);
        response.getHeader().setMsgId(uri);
        response.getHeader().setExpand(args);
        Object obj = JSONArray.toJSON(response);
        uri = obj.toString()+"$/r$\r\n";
        //String.format(SocketConfig.connectUri, conUser, conUser,RandomUtils.getShortUuid(),deviceid, RandomUtils.uuid(), code, args);
        ret = sendBySocket(uri, SocketConfig.homeIp, SocketConfig.NewPort);
        return ret;
    }
}


class ResponseMsg {

    private MsgHeader header;
    private String body;
    public void setHeader(MsgHeader header) {
        this.header = header;
    }
    public MsgHeader getHeader() {
        return header;
    }

    public void setBody(String body) {
        this.body = body;
    }
    public String getBody() {
        return body;
    }

}
